package com.fourhats.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fourhats.dao.MarketDAO;
import com.fourhats.model.Market;

@Repository
public class MarketDAOImpl extends GenericDAOImpl<Market, Long> implements MarketDAO {

	protected MarketDAOImpl() {
		super(Market.class.getName());
	}

	@SuppressWarnings("unchecked")
	public List<Market> getMarketsByKeyword(String keyword) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
        criteria.add(Restrictions.ilike("name", keyword, MatchMode.ANYWHERE));
        criteria.add(Restrictions.eq("enable", true));
        criteria.addOrder(Order.asc("name"));
        return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List<Market> getRandomlyHighlightMarkets(int maxResult) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
        criteria.add(Restrictions.eq("highlight", true));
        criteria.add(Restrictions.eq("enable", true));
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        List<Market> markets = getHibernateTemplate().findByCriteria(criteria, 0, maxResult*5);
        java.util.Collections.shuffle(markets);
        maxResult = maxResult < markets.size() ? maxResult : markets.size();
        return markets.subList(0, maxResult);
	}

	@SuppressWarnings("unchecked")
	public List<Market> getAllMarkets() {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
        criteria.add(Restrictions.eq("enable", true));
        criteria.addOrder(Order.asc("name"));
        return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public Market getMarketByUser(long userId) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		criteria.add(Restrictions.eq("user.id", userId));
		List<Market> markets = getHibernateTemplate().findByCriteria(criteria);
		if(!markets.isEmpty()) {
			return markets.get(0);
		}
		
		return null;
	}
	
	public boolean hasMarket(long userId) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		criteria.add(Restrictions.eq("user.id", userId));
		return !getHibernateTemplate().findByCriteria(criteria).isEmpty();
	}
	
	public boolean existMarketWithName(String marketName, long userId) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		criteria.add(Restrictions.eq("name", marketName));
		criteria.add(Restrictions.not(Restrictions.eq("user.id", userId)));
		return !getHibernateTemplate().findByCriteria(criteria).isEmpty();
	}
}